import axios from 'axios';
import store from '../store'

const service = axios.create({
    // baseURL: 'http://root@10.52.128.84:8089/api/v1',
    baseURL: process.env.BASE_API,
    timeout: 6000
});

// 设置请求次数，请求的间隙
// service.defaults.retry = 4;
// service.defaults.retryDelay = 1000;
// 添加请求拦截器
service.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么
        // 判断是否存在token，如果存在将每个页面header都添加token
        if(store.state.token){
            config.headers.common['Authentication-Token']=store.state.token
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error );
    }
);
// http response 拦截器
service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return response.data;
        } else {
            Promise.reject();
        }
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

export const post = (url, data = {}) => {
    return axios({
        method: 'post',
        url,
        data: data,
        timeout: 1000 * 60 * 3,
    })
}

export const get = (url, params = {}) => {
    return axios({
        method: 'get',
        url,
        params, // get 请求时带的参数
        timeout: 1000 * 60 * 3,
        headers: {
        }
    })
}

export const del = (url, params = {}) => {
    return axios({
        method: 'delete',
        url,
        params, // get 请求时带的参数
        timeout: 10000,
        headers: {
        }
    })
}

export const token = () => {
    return JSON.parse(localStorage.getItem('token'))
}
// 自定义上传文件
// export const myupload = (params = {}) => {
//     return axios({
//         method: 'post',
//         url: "/v1/user/abstract_dggd3/2",
//         // params, // get 请求时带的参数
//         timeout: 1000 * 60 * 3,
//             headers: {
//               'Content-Type': 'multipart/form-data',
//               changeOrigin: true, // 跨域
//               access_token: localStorage.getItem("token"),
//             },
//         data:params
//     })
// }

/**
 * 文件上传
 */
export function fileUpload(fileobj) {
    // let param = new FormData()
    // param.append('files',fileobj.file)
    return axios({
        method: 'post',
        url: "/v1/user/abstract_dggd3/2?access_token=" + JSON.parse(localStorage.getItem('token')),
        headers: {'Content-Type':'multipart/form-data'},
        data: fileobj.file
    })
}
export default service;
